############## 
############## 
############## Models
remove(list = ls())

base::library(conflicted)
base::library(tidyverse)
conflict_prefer("filter","dplyr")
base::library(ggplot2)
base::library(dplyr)
base::library(here)
conflict_prefer("here", "here")
base::library(stargazer)
base::library(DataCombine)
base::library(haven)
base::library(nnet)
base::library(ggeffects)

load(here("Data", "IndLevel_Data.RData"))

#log_death, death_rate, 
summary(ind_model <- multinom(fac_outcome ~ death_rate + unemp_rate + defl_pcincome +
                                log_pop + rural_urban + defl_pcincome + pid7 +
                                gender + black + hispanic + asian + other_race + 
                                log_age + college + income + year_elec, 
                              data = ces_data, weights = weight_cumulative))
#summary(ind_model)
library(sandwich)
#coeffs_cl <- coeftest(ind_model, vcov = vcovCL, cluster = ~ fips)
#coeffs_cl

summary(ces_data$death_rate)
model_drugs <- ind_model %>% 
  ggeffect(terms = c("death_rate[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]"), 
           ci.lvl = 0.95)
glimpse(model_drugs)
table(model_drugs$response.level)
class(model_drugs)

model_drugs <- data.frame(model_drugs)

rep_vote <- model_drugs %>% filter(response.level == "Rep")
  

g_abst <- model_drugs %>% 
  mutate(response = factor(response.level,
                           levels = c("Dem", 
                                      "Rep",
                                      "Abst"),
                           labels = c("Democratic", 
                                      "Republican",
                                      "Abstention"))) %>% 
  ggplot(aes(shape = response, color = response)) + 
  geom_pointrange(aes(x = x, y = predicted, 
                      ymin = conf.low, ymax = conf.high),
                  lwd = .85#, position = position_dodge(width = .5),
                  #color = "darkslategray"
                  ) + 
  theme_light() + 
  labs(x = "Overdose Death Rate", y = "Predicted Probability",
       title = NULL) +
  scale_shape_manual(name = "Vote Choice:",
                     labels = c("Democratic", "Republican", "Abstention"),
                     values = c(15, 16, 17)) +
  scale_color_manual(name = "Vote Choice:",
                     labels = c("Democratic", "Republican", "Abstention"),
                     values = c("blue", "red", "gray40")) +
  scale_x_continuous(breaks = c(0, 20, 40, 60, 80, 100, 120), lim = c(-1, 121)) +
  scale_y_continuous(breaks = c(0, 0.2, 0.4, 0.6), lim = c(0, 0.65)) +
  theme(axis.text.x = element_text(hjust = 0.5, size = 11),
        axis.text.y = element_text(size = 11),
        axis.title.y = element_text(size = 12),
        legend.text = element_text(size = 12),
        legend.title = element_text(size = 12),
        legend.position = "bottom",
        legend.direction = "horizontal",
        plot.title = element_text(size = 15))

g_abst

